package com.example.demo.navigation;

import com.example.demo.navigation.bean.NavBean;
import com.example.demo.navigation.service.NavService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("Admin/navigation")
public class NavigationController {

    private static final String rootName = "navigation/";

    @Autowired
    NavService navService;

    @RequestMapping("navlist")
    public String navigationList(Model model){
        model.addAttribute("navlist",navService.getList());
        return rootName+"navigationlist";
    }


    @RequestMapping(value = "addnav",method = RequestMethod.GET)
    public String addNav(Model model){
        model.addAttribute("parentlist",navService.getList(0));
        model.addAttribute("entity",new NavBean());
        return rootName+"addnav";
    }

    @RequestMapping("savenav")
    public String saveNav(@ModelAttribute("entity") @Valid NavBean navBean, BindingResult result){

        if (result.hasErrors()){
            return rootName+"addnav";
        }

        navService.addEntity(navBean);
        return "redirect:/Admin/navigation/navlist";
    }

    @RequestMapping("delnav/{id}")
    public String delNav(@PathVariable int id){
        navService.delEntity(id);
        return "redirect:/Admin/navigation/navlist";
    }

    @RequestMapping("nav/{id}")
    @ResponseBody
    public List<NavBean> navById(@PathVariable int id){
        return navService.getList(1,id);
    }

    @RequestMapping("test")
    public void test(){
        NavBean pn = navService.getById(1);
        System.out.println(pn.getChildren().size());
    }

    @RequestMapping("editnav/{id}")
    public String editNav(@PathVariable int id,Model model){

        NavBean bean = navService.getById(id);
        model.addAttribute("parentlist",navService.getList(0));

        if (bean.getType()==2){
            model.addAttribute("parentlist2",bean.getParent().getParent().getChildren());
        }
        model.addAttribute("entity",bean);
        return rootName+"addnav";
    }
}
